﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ElectricityInquery
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            try
            {
                string result = await Query();
                if (result == "0.0" || result == null)
                    throw new Exception();
                await DisplayAlert("提示", "剩余电量：" + result + "度", "确定");
            }
            catch
            {
                await DisplayAlert("错误", "输入参数有误！", "确定");
            }
        }

        private Task<string> Query()
        {
            TaskCompletionSource<string> result = new TaskCompletionSource<string>();
            string LayerNumber = Layer.Text.Trim(), RoomNumber = Room.Text.Trim(), Posit = West.IsChecked ? "1" : "0";
            string Url = "http://h5cloud.17wanxiao.com:8080/CloudPayment/user/getRoomState.do?payProId=726&schoolcode=43&businesstype=2&roomverify=-36--" + LayerNumber + "-" + Posit + LayerNumber + RoomNumber;
            new Thread(() =>
            {
                try
                {
                    WebClient webClient = new WebClient();
                    byte[] pageData = webClient.DownloadData(Url);
                    string pattern = "(?<=quantity\":\")(.*?)(?=\",\"q)";
                    Match match = Regex.Match(Encoding.GetEncoding("utf-8").GetString(pageData), pattern);
                    while (!match.Success)
                    {
                        result.SetResult(null);
                    }
                    result.SetResult(match.Value);
                }
                catch
                {
                    result.SetResult("0.0");
                }
            }
            )
            { IsBackground = true }.Start();
            return result.Task;
        }
    }
}
